package com.lecture.java8.multithreading;

/**
 * @author luyn
 * @version 1.0
 * @description 创建多线程 创建三个窗口卖票，总票数为100张
 * 1：使用同步代码块解决
 * @date 2021/1/13 20:06
 */
public class WindowTest {
    public static void main(String[] args) {
        Window w1 = new Window();
        Window w2 = new Window();
        Window w3 = new Window();
        w1.setName("窗口1：");
        w2.setName("窗口2：");
        w3.setName("窗口3：");
        w1.start();
        w2.start();
        w3.start();
    }
}

class Window extends Thread{
    private static int ticket = 100;

    private static Object obj = new Object();

    @Override
    public void run() {
        while (true) {
           synchronized (obj) {
               if (ticket > 0) {
                   try {
                       Thread.sleep(100);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   System.out.println(this.getName() + "：卖票，票号为：" + ticket);
                   ticket--;
               } else {
                   break;
               }
           }
        }
    }
}
